//
//  userEditViewController.m
//  jingdongfang
//
//  Created by MTiMac02 on 2017/8/16.
//  Copyright © 2017年 kevinLY. All rights reserved.
//

#import "userEditViewController.h"
#import "addGalleryViewController.h"
#import "IconCollectionViewCell.h"
#import "AddDvViewController.h"
#import "IconHorizontalFlowLayout.h"
#import "PictureUpLoad.h"
#import "IGOSSManager.h"
#import "IGUpdateImageApi.h"
#import "IGUpdateNikeApi.h"

@interface userEditViewController ()<UITextFieldDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource>{
    NSString *nickString;
    UIImageView *icon;
}

@property (weak, nonatomic)UITextField *textField;
@property (nonatomic, strong) UICollectionView *IconCollect;
@property (nonatomic, strong) NSArray *itemTitles;
@property(strong,nonatomic)UIImageView *useView;
@property(strong,nonatomic)UIImageView *useHeadView;
@property(strong,nonatomic) IGUpdateNikeApi *updateNickApi;

@end


@implementation userEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.title=@"编辑个人资料";
    self.title=NSLocalizedString(@"Edit Personal Profile", nil);
    [[IGOSSManager sharedManager] requestOssToken:IGAliYunFolderTypeUser];
    
//    [self ig_setupRightButtonItemWithTitle:@"跳过" image:nil highLightedImage:nil];
    [self ig_setupRightButtonItemWithTitle:NSLocalizedString(@"Skip", nil) image:nil highLightedImage:nil];

    self.itemTitles=@[@"avatar_达芬奇",@"avatar_朵拉玛尔",@"avatar_梵高",@"avatar_拉斐尔",@"avatar_罗塞蒂",@"avatar_莫奈"];
    [self setUI];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.IconCollect selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
    });
    
    if (self.firstLogin) {
        [self ig_setupLeftBarButtonItemWithTitle:@"" image:nil highLightedImage:nil];
    }
}

- (void)ig_leftButtonPressed:(id)sender {
    
}

-(void)setUI {
    IconHorizontalFlowLayout  *layout = [[IconHorizontalFlowLayout alloc] init];
    layout.minimumLineSpacing=20;
    layout.minimumInteritemSpacing=100;
    UICollectionView *collect=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, KSCREENWIDTH, 190) collectionViewLayout:layout];
    collect.backgroundColor=[UIColor clearColor];
    _IconCollect=collect;
    collect.delegate=self;
    collect.dataSource=self;
    collect.showsHorizontalScrollIndicator = NO;
    collect.showsVerticalScrollIndicator=NO;
    [collect registerClass:[IconCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([IconCollectionViewCell class])];
    collect.hidden=NO;
    [self.view addSubview:collect];
    
    UIImageView *userView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 64, KSCREENWIDTH, 190)];
    userView.image=[UIImage imageNamed:@"背景-个人资料"];
    _useView=userView;
    UIImageView *userImage=[[UIImageView alloc]initWithFrame:CGRectMake(KSCREENWIDTH/2-45, 45, GSCALE(110),GSCALE(110))];
    icon=userImage;
    userImage.contentMode=UIViewContentModeScaleAspectFill;
    userImage.layer.cornerRadius=userImage.width/2;
    userImage.layer.masksToBounds=YES;
    userImage.image=[UIImage imageNamed:@"classification1"];
    userView.hidden=YES;
    [userView addSubview:userImage];
    [self.view addSubview:userView];
    
    UIImageView *useHeadView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    useHeadView.image=[UIImage imageNamed:@"avatar_梵高"];
    useHeadView.layer.cornerRadius=40;
    useHeadView.layer.masksToBounds=YES;
    useHeadView.top = userView.bottom;
    useHeadView.centerX=KSCREENWIDTH/2;
    useHeadView.userInteractionEnabled = YES;
    [useHeadView setTapActionWithBlock:^{
        [self chang];
    }];
    _useHeadView=useHeadView;
    [self.view addSubview:useHeadView];
    
    UIButton *iconbtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [iconbtn setImage:[UIImage imageNamed:@"btn-上传头像"] forState:UIControlStateNormal];
    iconbtn.frame=CGRectMake(0, 0, 24, 24);
    iconbtn.centerX=KSCREENWIDTH/2;
    iconbtn.top=collect.bottom+8;
    [iconbtn addTarget:self action:@selector(chang) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:iconbtn];
    
    UILabel * uplable=[[UILabel alloc]initWithFrame:CGRectZero];
//    uplable.text=@"上传头像";
    uplable.text=NSLocalizedString(@"Upload Image", nil);

    uplable.font=[UIFont font16];
    uplable.textColor=[UIColor c3Color];
    [uplable sizeToFit];
    uplable.top=iconbtn.bottom+8;
    uplable.centerX=iconbtn.centerX;
    uplable.textAlignment=NSTextAlignmentCenter;
    [self.view addSubview:uplable];
    
    UILabel *nickLabel=[[UILabel alloc]initWithFrame:CGRectZero];
//    nickLabel.text=@"昵称";
    nickLabel.text=NSLocalizedString(@"Nickname", nil);
    nickLabel.font=[UIFont font18];
    nickLabel.textColor=[UIColor c5Color];
    [nickLabel sizeToFit];
    nickLabel.width=nickLabel.width+30;
    
    UITextField *nicktField=[[UITextField alloc]initWithFrame:CGRectMake(0, 0, GSCALE(300), GSCALE(45))];
    nicktField.leftViewMode=UITextFieldViewModeAlways;
    nicktField.delegate=self;
//    nicktField.placeholder=@"请输入您的昵称";
    nicktField.placeholder=NSLocalizedString(@"Your Nickname", nil);

    nicktField.text=nickString;
    nicktField.textAlignment=NSTextAlignmentLeft;
    nicktField.textColor=[UIColor c4Color];
    nicktField.font=[UIFont font18];
    nicktField.top=uplable.bottom+40;
    nicktField.centerX=uplable.centerX;
    nicktField.borderStyle= UITextBorderStyleNone;
    nicktField.clearsOnBeginEditing=YES;
    nicktField.clearButtonMode=UITextFieldViewModeWhileEditing;
    [nicktField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    self.textField=nicktField;
    nicktField.leftView=nickLabel;
    [self.view addSubview:nicktField];
    
    UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, GSCALE(300), 1)];
    line.backgroundColor=[UIColor c6Color];
    line.top=nicktField.bottom;
    line.centerX=nicktField.centerX;
    [self.view addSubview:line];
    
    UIButton *saveBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [saveBtn.layer setCornerRadius:20.f];
    saveBtn.backgroundColor=[UIColor appColor];
//    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitle:NSLocalizedString(@"Save", nil) forState:UIControlStateNormal];
    saveBtn.titleLabel.font=[UIFont font16];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    saveBtn.size=CGSizeMake(GSCALE(300), GSCALE(44));
    saveBtn.top=nicktField.bottom+25;
    saveBtn.centerX=nicktField.centerX;
    [saveBtn addTarget:self action:@selector(saveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveBtn];
}

#pragma mark---UICollectionViewDelegateFlowLayout,UICollectionViewDelegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.itemTitles count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    IconCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([IconCollectionViewCell class]) forIndexPath:indexPath];
    
    cell.image.image = [UIImage imageNamed:[self.itemTitles objectAtIndex:indexPath.row]];
    
    return cell;
}

- (CGSize)collectionView:(nonnull UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return CGSizeMake(GSCALE(90), GSCALE(90));
}

- (UIEdgeInsets)collectionView:(nonnull UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    NSInteger itemCount = [self collectionView:collectionView numberOfItemsInSection:section];
    NSIndexPath *firstIndexPath = [NSIndexPath indexPathForItem:0 inSection:section];
    CGSize firstSize = [self collectionView:collectionView layout:collectionViewLayout sizeForItemAtIndexPath:firstIndexPath];
    
    NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:itemCount - 1 inSection:section];
    CGSize lastSize = [self collectionView:collectionView layout:collectionViewLayout sizeForItemAtIndexPath:lastIndexPath];
    
    return UIEdgeInsetsMake(-45, (collectionView.bounds.size.width - firstSize.width) / 2,
                            0, (collectionView.bounds.size.width - lastSize.width) / 2);
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.IconCollect selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
    
    _useHeadView.image = [UIImage imageNamed:self.itemTitles[indexPath.row]];
}

- (void)chang {
    __weak typeof(self) weakSelf = self;
    [IGPermissionUtil ig_showActionSheetWithCameraBlock:^{
        [IGTakePhotosUtil ig_showImagePickerControllerWithImagePickerBlock:^ (NSDictionary<NSString *,id> * _Nullable info){
            if (info) {
                UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
                image = [image fixOrientation];
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.useHeadView.image = image;
                });
            }
        }];
    } photoBlock:^{
        [IGTakePhotosUtil ig_showAssetsPickerControllerWithMaximumNumberOfSelection:1 assetsPickerBlock:^(NSArray * _Nonnull assets) {
            if (assets.count != 0) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.useHeadView.image = assets[0];
                });
            }
        }];
    }];
}

- (IBAction)saveBtnClick:(id)sender {
    [self.view endEditing:YES];
//    [self showText:@"正在提交..."];
    [self showText:NSLocalizedString(@"Submitting", nil)];
    nickString = _textField.text;
    if (nickString.length == 0) {
//        [self presentMessageTips:@"请输入昵称"];
        [self presentMessageTips:NSLocalizedString(@"Please Input Nickname", nil)];
        return;
    }
    
    BOOL ishas = [NSString stringContainsEmoji:nickString];
    if (ishas) {
//        [self presentMessageTips:@"不支持表情符号"];
        [self presentMessageTips:NSLocalizedString(@"Emoji Unavailable", nil)];
        return;
    }
    
    [self uploadToAliyun:@[_useHeadView.image]];
}

- (void)uploadToAliyun:(NSArray *)images {
    [[IGOSSManager sharedManager] asyncPutImages:images withCompleteBlock:^(NSArray *params, NSArray *urls) {
        if (params.count != 0)  {
            [self updataImage:params.firstObject];
        } else  {
//            [self presentMessageTips:@"提交失败"];
            [self presentMessageTips:NSLocalizedString(@"Submitting Failed", nil)];
        }
    }];
}

- (void)updataImage:(NSString *)str
{
    IGUpdateImageApi *api = [IGUpdateImageApi new];
    api.image = str;
    [api startWithDecodeClass:[IGUpdateImageResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            [self updateNick];
            [IGUser saveImage:str];
        } else {
//            [self presentMessageTips:@"提交失败"];
            [self presentMessageTips:NSLocalizedString(@"Submitting Failed", nil)];
        }
    }];
}

- (void)updateNick {
    self.updateNickApi=[[IGUpdateNikeApi alloc]initWithUid:[IGUser getUid] nike:nickString];
    [self.updateNickApi startWithDecodeClass:[IGUpdateNikeResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            [IGUser saveNike:nickString];
            [self dismissLoading];
            [UIViewController ig_pushViewControllerClass:[addGalleryViewController class] animated:YES];
        } else {
//            [self presentMessageTips:@"昵称提交失败"];
            [self presentMessageTips:NSLocalizedString(@"Nickname Submitting Failed", nil)];
        }
    }];
}

- (void)ig_rightButtonPressed:(id)sender {
    [UIViewController ig_pushViewControllerClass:[addGalleryViewController class] animated:YES];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.textField resignFirstResponder];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    return [textField resignFirstResponder];
}

- (void)textChange:(UITextField *)textField {
    if (textField.text.length>10) {
        textField.text = [textField.text substringToIndex:10];
    }
    nickString = textField.text;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
